package com.itzxx.huazhun.data.repository

import android.content.Context
import android.text.TextUtils
import com.alibaba.sdk.android.oss.ClientConfiguration
import com.alibaba.sdk.android.oss.OSS
import com.alibaba.sdk.android.oss.OSSClient
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider
import com.alibaba.sdk.android.oss.common.auth.OSSStsTokenCredentialProvider
import com.alibaba.sdk.android.oss.model.PutObjectRequest
import com.itzxx.huazhun.data.dao.CollectionEntity
import com.itzxx.huazhun.data.dao.DbHelper
import com.itzxx.huazhun.data.model.CalculationLocalResult
import com.itzxx.huazhun.data.model.CalculationResultsBean
import com.itzxx.huazhun.data.model.ComplianceResult
import com.itzxx.huazhun.data.model.DeviceType
import com.itzxx.huazhun.data.model.DevicesBean
import com.itzxx.huazhun.data.model.DevicesChildBean
import com.itzxx.huazhun.data.model.LoginUser
import com.itzxx.huazhun.data.model.ProbeAllInfo
import com.itzxx.huazhun.data.model.ProbeRecordBean
import com.itzxx.huazhun.data.model.RecordBean
import com.itzxx.huazhun.data.model.RecordCurveAdminDataBean
import com.itzxx.huazhun.data.model.RecordCurveDataBean
import com.itzxx.huazhun.data.model.RecordCurveListDataBean
import com.itzxx.huazhun.data.model.SceneTypeBean
import com.itzxx.huazhun.data.model.UserAuditInfo
import com.itzxx.huazhun.data.model.UserInfo
import com.itzxx.huazhun.data.model.UserListInfo
import com.itzxx.huazhun.data.model.UserPermissionInfo
import com.itzxx.huazhun.network.ApiResponse
import com.itzxx.huazhun.network.ApiService
import com.itzxx.huazhun.network.NetworkApi
import com.itzxx.huazhun.utils.DateUtil
import com.itzxx.huazhun.utils.ExcelUtil
import com.itzxx.huazhun.utils.Snowflake
import com.itzxx.huazhun.utils.UserCacheHelper
import com.itzxx.library_base_ktx.ext.util.toRequestBody
import com.itzxx.library_base_ktx.network.AppException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.util.TreeMap
import kotlin.math.abs
import kotlin.math.pow


val HttpRequestCoroutine: HttpRequestManger by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
    HttpRequestManger()
}


class HttpRequestManger {

    private var apiService: ApiService =
        NetworkApi.INSTANCE.getApi(ApiService::class.java, ApiService.SERVER_URL)

    suspend fun login(
        mechanismName: String, username: String, pwd: String
    ): ApiResponse<LoginUser> {
        return withContext(Dispatchers.IO) {
            val empty = TreeMap<String, Any>()
            empty.put("tenantName", mechanismName)
            val tenantData = apiService.getTenantIdByName(empty.toRequestBody())

            if (tenantData.isSucces()) {
                empty.clear()
                empty.put("username", username)
                empty.put("password", pwd)
                //租户id
                UserCacheHelper.putTenantId(tenantData.data)
                val loginUserApiResponse = apiService.login(empty.toRequestBody())
                if (loginUserApiResponse.isSucces()) {
                    //用户token
                    UserCacheHelper.putToken(loginUserApiResponse.data.accessToken)
                    UserCacheHelper.putRefreshToken(loginUserApiResponse.data.refreshToken)
                    val userPermissionInfoApiResponse = getPermissionInfo()
                    if (userPermissionInfoApiResponse.isSucces()) {
                        //用户权限
                        UserCacheHelper.putUserPermission(userPermissionInfoApiResponse.data)
                        //保存密码
                        UserCacheHelper.putPassword(pwd)
                    } else {
                        UserCacheHelper.putToken("")
                        UserCacheHelper.putTenantId("")
                        //抛出错误异常
                        throw AppException(
                            userPermissionInfoApiResponse.code, userPermissionInfoApiResponse.msg
                        )
                    }
                } else {
                    UserCacheHelper.putToken("")
                    UserCacheHelper.putTenantId("")
                }
                loginUserApiResponse
            } else {
                UserCacheHelper.putToken("")
                UserCacheHelper.putTenantId("")
                //抛出错误异常
                throw AppException(tenantData.code, tenantData.msg)
            }
        }
    }

    fun doRefreshToken(): ApiResponse<LoginUser> {
        val empty = TreeMap<String, Any>()
        empty["refreshToken"] = UserCacheHelper.getRefreshToken()
        val loginUserApiResponse = apiService.doRefreshToken(empty.toRequestBody())
        if (loginUserApiResponse.isSucces()) {
            //用户token
            UserCacheHelper.putToken(loginUserApiResponse.data.accessToken)
            UserCacheHelper.putRefreshToken(loginUserApiResponse.data.refreshToken)
        }
        return loginUserApiResponse
    }

    /**
     * 用户注册
     */
    suspend fun userRegister(empty: TreeMap<String, Any>): ApiResponse<Any> {
        return withContext(Dispatchers.IO) {
            val queryTenantIdByName = TreeMap<String, Any>()
            empty.get("tenantName")?.let { queryTenantIdByName.put("tenantName", it) }
            val tenantData = apiService.getTenantIdByName(queryTenantIdByName.toRequestBody())
            if (tenantData.isSucces()) {
                empty.put("tenantId", tenantData.data)
                apiService.userRegister(empty.toRequestBody())
            } else {
                //抛出错误异常
                throw AppException(tenantData.code, tenantData.msg)
            }
        }
    }

    /**
     * 获取权限
     */
    suspend fun getPermissionInfo(): ApiResponse<UserPermissionInfo> {
        return apiService.getPermissionInfo()
    }


    suspend fun getUserInfo(): ApiResponse<UserInfo> {
        return apiService.getUserInfo()
    }

    suspend fun getUserAuditList(cursor: String): ApiResponse<UserAuditInfo> {
        val empty = TreeMap<String, Any>()
        empty.put("cursor", cursor)
        empty.put("pageSize", 20)
        return apiService.getUserAuditList(empty.toRequestBody())
    }

    /**
     * 审批结果
     */
    suspend fun doUserAuditHandle(
        id: Int, applicantName: String, approvalStatus: Int, refuseRemark: String
    ): ApiResponse<Boolean> {
        val empty = TreeMap<String, Any>()
        empty.put("id", id)
        empty.put("applicationName", applicantName)
        empty.put("approvalStatus", approvalStatus)
        empty.put("refuseRemark", refuseRemark)
        return apiService.doUserAuditHandle(empty.toRequestBody())
    }

    /**
     * 成员列表分页
     */
    suspend fun queryMemberListPage(cursor: String): ApiResponse<UserListInfo> {
        val empty = TreeMap<String, Any>()
        empty.put("cursor", cursor)
        empty.put("pageSize", 20)
        return apiService.queryMemberListPage(empty.toRequestBody())
    }

    /**
     * 检测设备列表
     */
    suspend fun detectionEquipmentPage(
        cursor: String,
        deviceName: String
    ): ApiResponse<DevicesBean> {
        val empty = TreeMap<String, Any>()
        empty.put("cursor", cursor)
        empty.put("deviceName", deviceName)
        empty.put("pageSize", 20)
        return apiService.detectionEquipmentPage(empty.toRequestBody())
    }


    /**
     * 检测设备详情
     */
    suspend fun detectionEquipmentInfo(
        id: Int,
        equipmentNo: String
    ): ApiResponse<DevicesChildBean> {
        val empty = TreeMap<String, Any>()
        empty.put("id", id)
        empty.put("equipmentNo", equipmentNo)
        return apiService.detectionEquipmentInfo(empty.toRequestBody())
    }


    /**
     * 检测设备详情
     */
    suspend fun addDetectionEquipment(empty: TreeMap<String, Any>): ApiResponse<Boolean> {
        return apiService.addDetectionEquipment(empty.toRequestBody())
    }

    /**
     * 检测设备类型
     */
    suspend fun getEquipmentType(): ApiResponse<ArrayList<DeviceType>> {
        return apiService.getEquipmentType()
    }

    /**
     * 探头采集记录列表
     */
    suspend fun probeCollectionPage(
        equipmentName: String = "",
        cursor: String,
    ): ApiResponse<RecordBean> {
        val empty = TreeMap<String, Any>()
        empty.put("equipmentName", equipmentName)
        empty.put("cursor", cursor)
        empty.put("pageSize", 20)
        return apiService.probeCollectionPage(empty.toRequestBody())
    }

    /**
     * 探头采集记录列表
     */
    suspend fun delProbeRecordCollection(
        id: String = ""
    ): ApiResponse<Boolean> {
        val empty = TreeMap<String, Any>()
        empty.put("id", id)
        return apiService.delProbeRecordCollection(empty.toRequestBody())
    }


    /**
     * 上传采集记录
     */
    suspend fun uploadProbeCollection(
        context: Context,
        collectionEntity: CollectionEntity
    ): ApiResponse<Boolean> {
        return withContext(Dispatchers.IO) {
            val probeRecordList = DbHelper.init().getProbeRecordDao()
                .getProbeRecordList(collectionEntity.probe_mac, collectionEntity.recordStartTime)
            if (probeRecordList.isEmpty()) {
                throw AppException(1003, "数据收集异常，请重新处理！！！")
            }
            val empty = TreeMap<String, Any>()
            empty["mac"] = collectionEntity.probe_mac.replace(":", "")
            empty["softwareVersion"] = collectionEntity.sw
            empty["hardwareVersion"] = collectionEntity.hw
            empty["battery"] = collectionEntity.battery
            empty["capacity"] = collectionEntity.feature
            empty["channelNum"] = collectionEntity.wayNum
            empty["channelList"] =
                collectionEntity.wayIndex.replace("[", "").replace("]", "").replace(" ", "")
            empty["samplingInterval"] = collectionEntity.recordSamplingInterval
            empty["model"] = collectionEntity.model
            empty["recordNum"] = collectionEntity.recordNum
            empty["startTime"] =
                DateUtil.getYMDHMSStr("${collectionEntity.recordStartTime}000".toLong())
            val dataList = arrayListOf<ProbeRecordBean>()
            for ((index, probeRecordEntity) in probeRecordList.withIndex()) {
                val time = DateUtil.getYMDHMSStr((probeRecordEntity.recordStartTime + "000").toLong() + index * probeRecordEntity.recordSamplingInterval.toLong() * 1000)
                dataList.add(
                    ProbeRecordBean(
                        time,
                        probeRecordEntity.airPressure.toString(),
                        probeRecordEntity.temperature.toString()
                    )
                )
            }
            empty["data"] = dataList
            val uploadProbeData = apiService.uploadProbeData(empty.toRequestBody())
            if (uploadProbeData.isSucces()){
                collectionEntity.state = 1
                //上传url成功
                DbHelper.init().getCollectionDao().update(collectionEntity)
            }
            uploadProbeData
        }
    }


    /**
     * 探头采集记录列表
     */
    suspend fun getCollectionRecordList(): ApiResponse<List<CollectionEntity>> {
        return withContext(Dispatchers.IO) {
            val collectionRecordList = DbHelper.init().getCollectionDao().getCollectionRecordList()
            ApiResponse(0, "", collectionRecordList)
        }
    }

    /**
     * 采集数据曲线
     */
    suspend fun queryEquipmentDataCurve(
        id: String
    ): ApiResponse<RecordCurveDataBean> {
        val empty = TreeMap<String, Any>()
        empty.put("id", id)
        return apiService.queryEquipmentDataCurve(empty.toRequestBody())
    }

    /**
     * 测量数据明细分页
     */
    suspend fun queryMeasurementDataDetailsPage(
        id: String,
        cursor: String
    ): ApiResponse<RecordCurveListDataBean> {
        val empty = TreeMap<String, Any>()
        empty["id"] = id
        empty["cursor"] = cursor
        empty["pageSize"] = 50
        return apiService.queryMeasurementDataDetailsPage(empty.toRequestBody())
    }

    /**
     * 指定协调器记录关联设备
     */
    suspend fun bindProbeDataById(
        id: List<Int>,
        equipmentId: String,
        equipmentName: String,
        equipmentNo: String,
        runProgram: String,
    ): ApiResponse<Boolean> {
        val empty = TreeMap<String, Any>()
        empty["id"] = id
        empty["equipmentId"] = equipmentId
        empty["equipmentName"] = equipmentName
        empty["equipmentNo"] = equipmentNo
        empty["runProgram"] = runProgram
        return apiService.bindProbeDataById(empty.toRequestBody())
    }

    suspend fun querySceneType(): ApiResponse<ArrayList<SceneTypeBean>> {
        return apiService.querySceneType()
    }

    /**
     * 根据场景获取数值
     */
    suspend fun queryNumericalValueByScene(
        ids: ArrayList<Int>,
        sceneType: Int,
        wd: Double
    ): ApiResponse<CalculationResultsBean> {
        val empty = TreeMap<String, Any>()
        empty["ids"] = ids
        empty["sceneType"] = sceneType
        empty["wd"] = wd
        return apiService.queryNumericalValueByScene(empty.toRequestBody())
    }

    /**
     * 采集数据曲线
     */
    suspend fun queryAdminEquipmentDataCurve(
        ids: ArrayList<Int>,
        sceneType: Int,
        startTime: String,
        endTime: String
    ): ApiResponse<ArrayList<RecordCurveAdminDataBean>> {
        val empty = TreeMap<String, Any>()
        empty["ids"] = ids
        empty["sceneType"] = sceneType
        empty["startTime"] = startTime
        empty["endTime"] = endTime
        return apiService.queryAdminEquipmentDataCurve(empty.toRequestBody())
    }


    suspend fun onValuationResult(
        sceneType: Int,
        ids: ArrayList<Int>,
        wd: Double
    ): ApiResponse<CalculationLocalResult> = withContext(Dispatchers.IO) {
        //返回数据
        val calculationLocalResult = CalculationLocalResult()
        val collectionRecordList = DbHelper.init().getCollectionDao().getCollectionRecordList(ids)
        //两条或者以上存在相差3分钟
        var isExstErrorData = false
        if (collectionRecordList.size > 1) {
            for (i in collectionRecordList.indices) {
                val iCollectionEntity = collectionRecordList[i]
                for (j in collectionRecordList.indices) {
                    val jCollectionEntity = collectionRecordList[j]
                    //时间间隔差3分钟说明存在异常 数据
                    if (Math.abs(iCollectionEntity.recordStartTime.toLong() - jCollectionEntity.recordStartTime.toLong()) > 180) {
                        isExstErrorData = true
                    }
                }
            }
        }
        //异常 数据就一条一条判断直接返回数据
        if (isExstErrorData) {
            if (sceneType == 2) {
                val errorList = arrayListOf<String>()
                for (i in collectionRecordList.indices) {
                    val collectionEntity = collectionRecordList[i]
                    val probeRecordList = DbHelper.init().getProbeRecordDao().getProbeRecordList(
                        collectionEntity.probe_mac,
                        collectionEntity.recordStartTime
                    )
                    //达到次数
                    var numberOfTouches = 0
                    //所以达到的时间
                    val timeTouchesList = arrayListOf<String>()
                    probeRecordList.forEachIndexed { index, probeRecordEntity ->
                        if (probeRecordEntity.temperature >= wd) {
                            numberOfTouches++
                            timeTouchesList.add(DateUtil.formatHMSTime((probeRecordEntity.recordStartTime + "000").toLong() + index * probeRecordEntity.recordSamplingInterval.toLong() * 1000))
                        }
                    }
                    if (numberOfTouches > 0) {
                        errorList.add("第${i}个探头达到温度${wd}，开始时间:${timeTouchesList[0]},结束时间:${timeTouchesList[timeTouchesList.size - 1]},维持时间${numberOfTouches}秒")
                    } else {
                        errorList.add("第${i}个探头未达到温度${wd}")
                    }
                }
                calculationLocalResult.noComplianceResult = errorList.joinToString(separator = ", ")
            } else if (sceneType == 7) {
                calculationLocalResult.noComplianceResult = "数据异常，无法评估！"
            }
        } else {
            //评估后的说明
            val complianceResult = ComplianceResult()
            //高温灭菌和清晰消毒处理
            if (sceneType != 10) {
                //存放个个探头最大值
                val maxWenDuList = arrayListOf<Double>()
                //存放个个探头最小值
                val minWenDuList = arrayListOf<Double>()
                //存放个个探头平均值
                val avgWenDuList = arrayListOf<Double>()
                for (i in collectionRecordList.indices) {
                    val collectionEntity = collectionRecordList[i]
                    if (collectionEntity.isExistTemp()) {
                        maxWenDuList.add(
                            DbHelper.init().getProbeRecordDao().getProbeRecordListTempMax(
                                collectionEntity.probe_mac,
                                collectionEntity.recordStartTime
                            )
                        )
                        minWenDuList.add(
                            DbHelper.init().getProbeRecordDao().getProbeRecordListTempMin(
                                collectionEntity.probe_mac,
                                collectionEntity.recordStartTime
                            )
                        )
                        avgWenDuList.add(
                            DbHelper.init().getProbeRecordDao().getProbeRecordListTempAvg(
                                collectionEntity.probe_mac,
                                collectionEntity.recordStartTime
                            )
                        )
                    }
                }
                //最高温度======================
                val maxWenDu = maxWenDuList.max()
                complianceResult.maximumTemperature = maxWenDu.toString()
                //======================高温灭菌======================
                if (sceneType == 2) {
                    //灭菌温度======================
                    complianceResult.sterilizationTemperature = wd.toString()
                    var isExistError = false
                    maxWenDuList.forEach {
                        if (it < wd) {
                            isExistError = true
                        }
                    }
                    //只要有一个未达标就不计算，直接显示哪个未达标
                    if (isExistError) {
                        val errorList = arrayListOf<String>()
                        for (i in collectionRecordList.indices) {
                            val collectionEntity = collectionRecordList[i]
                            val probeRecordList =
                                DbHelper.init().getProbeRecordDao().getProbeRecordList(
                                    collectionEntity.probe_mac,
                                    collectionEntity.recordStartTime
                                )
                            //达到次数
                            var numberOfTouches = 0
                            //所以达到的时间
                            val timeTouchesList = arrayListOf<String>()
                            probeRecordList.forEachIndexed { index, probeRecordEntity ->
                                if (probeRecordEntity.temperature >= wd) {
                                    numberOfTouches++
                                    timeTouchesList.add(DateUtil.formatHMSTime((probeRecordEntity.recordStartTime + "000").toLong() + index * probeRecordEntity.recordSamplingInterval.toLong() * 1000))
                                }
                            }
                            if (numberOfTouches > 0) {
                                errorList.add("第${i + 1}个探头达到温度${wd}°C，开始时间:${timeTouchesList[0]},结束时间:${timeTouchesList[timeTouchesList.size - 1]},维持时间${numberOfTouches}秒")
                            } else {
                                errorList.add("第${i + 1}个探头未达到温度${wd}°C")
                            }
                        }
                        calculationLocalResult.noComplianceResult =
                            errorList.joinToString(separator = ", ")
                    } else {
                        //最低温度======================
                        val minWenDu = minWenDuList.min()
                        complianceResult.minimumTemperature = minWenDu.toString()

                        //平衡时间======================
                        val balanceTimeList = arrayListOf<Long>()
                        for (i in collectionRecordList.indices) {
                            val collectionEntity = collectionRecordList[i]
                            //判断是否存在温度传感器
                            if (collectionEntity.isExistTemp()) {
                                //条件下所以数据
                                val probeRecordList = DbHelper.init().getProbeRecordDao()
                                    .getProbeRecordList(
                                        collectionEntity.probe_mac,
                                        collectionEntity.recordStartTime
                                    )
                                //第1个超过灭菌
                                val probeRecordFirstGreaterThan =
                                    DbHelper.init().getProbeRecordDao()
                                        .getProbeRecordTempFirstGreaterThan(
                                            collectionEntity.probe_mac,
                                            collectionEntity.recordStartTime,
                                            wd
                                        )
                                for (j in probeRecordList.indices) {
                                    if (probeRecordList[j].id == probeRecordFirstGreaterThan.id) {
                                        //开始时间+所在位置*间隔时间
                                        balanceTimeList.add(probeRecordList[j].recordStartTime.toLong() + j * probeRecordList[j].recordSamplingInterval.toInt())
                                        break
                                    }
                                }
                            }
                        }
                        //单个不计算
                        if (balanceTimeList.size <= 1) {
                            complianceResult.balanceTime = "0"
                        } else {
                            val maxBalanceTime = balanceTimeList.max()
                            val minBalanceTime = balanceTimeList.min()
                            complianceResult.balanceTime =
                                (maxBalanceTime - minBalanceTime).toString()
                        }
                        //维持时间======================
                        val maxStartMaintainTimeList = arrayListOf<Long>()
                        val mixEndMaintainTime = arrayListOf<Long>()
                        val probeRecordMapList = arrayListOf<HashMap<Long, Double>>()
                        for (i in collectionRecordList.indices) {
                            val collectionEntity = collectionRecordList[i]
                            maxStartMaintainTimeList.add(collectionEntity.recordStartTime.toLong())
                            mixEndMaintainTime.add(collectionEntity.recordStartTime.toLong() + collectionEntity.recordNum)
                            val probeRecordList = DbHelper.init().getProbeRecordDao()
                                .getProbeRecordList(
                                    collectionEntity.probe_mac,
                                    collectionEntity.recordStartTime
                                )
                            //key:时间。value:温度数值
                            val simgleProbeRecordMap = hashMapOf<Long, Double>()
                            probeRecordList.forEachIndexed { index, probeRecordEntity ->
                                simgleProbeRecordMap[probeRecordEntity.recordStartTime.toLong() + index] =
                                    probeRecordEntity.temperature
                            }
                            probeRecordMapList.add(simgleProbeRecordMap)
                        }
                        //这边开始取交集
                        val maxStartMaintainTime = maxStartMaintainTimeList.max()
                        val minEndMaintainTime = mixEndMaintainTime.min()
                        val allgreaterThanTimeList = arrayListOf<Long>()
                        for (i in maxStartMaintainTime..minEndMaintainTime) {
                            var allgreaterThan = true
                            //判断同一时间内的数值是否都大于指定的温度
                            for (hashMap in probeRecordMapList) {
                                val value = hashMap[i]
                                if (value == null || value < wd) {
                                    allgreaterThan = false
                                }
                            }
                            if (allgreaterThan) {
                                allgreaterThanTimeList.add(i)
                            } else if (allgreaterThanTimeList.size > 0) {
                                allgreaterThanTimeList.add(i)
                                break
                            }
                        }
                        //起始和结束
                        //维持时间计算完成
                        if (allgreaterThanTimeList.size >= 2) {
                            complianceResult.maintenanceTime =
                                (allgreaterThanTimeList[allgreaterThanTimeList.size - 1] - allgreaterThanTimeList[0]).toString()
                        }

                        //温度均匀度======================
                        // 温度均匀度：灭菌阶段的（每个探头的最高-最低温度）相加/ 灭菌阶段时间
                        var maxSubMinTotal = 0.0
                        //用于计算探头最大和最小
                        val maxSubMinCalculationList = mutableListOf<Double>()
                        //触发点区间
                        allgreaterThanTimeList.forEachIndexed { _, time ->
                            maxSubMinCalculationList.clear()
                            //多个个探头的map记录数据
                            probeRecordMapList.forEachIndexed { _, hashMap ->
                                hashMap[time]?.let {
                                    maxSubMinCalculationList.add(it)
                                }
                            }
                            maxSubMinTotal += (maxSubMinCalculationList.max() - maxSubMinCalculationList.min())
                        }
                        //计算
                        complianceResult.temperatureUniformity = (maxSubMinTotal/complianceResult.maintenanceTime.toLong()).toString()

                        //灭菌压力======================
                        //存放个个探头最大值
                        val maxAirPressureList = arrayListOf<Double>()
                        //存放个个探头最小值
                        val minAirPressureList = arrayListOf<Double>()
                        //存放个个探头平均值
                        val avgAirPressureList = arrayListOf<Double>()
                        for (i in collectionRecordList.indices) {
                            val collectionEntity = collectionRecordList[i]
                            //判断是否存在空气压力传感器
                            if (collectionEntity.isExistAirPressure()) {
                                //条件下所以数据
                                maxAirPressureList.add(
                                    DbHelper.init().getProbeRecordDao()
                                        .getProbeRecordListAirPressureMax(
                                            collectionEntity.probe_mac,
                                            collectionEntity.recordStartTime
                                        )
                                )
                                minAirPressureList.add(
                                    DbHelper.init().getProbeRecordDao()
                                        .getProbeRecordListAirPressureMin(
                                            collectionEntity.probe_mac,
                                            collectionEntity.recordStartTime
                                        )
                                )
                                avgAirPressureList.add(
                                    DbHelper.init().getProbeRecordDao()
                                        .getProbeRecordListAirPressureAvg(
                                            collectionEntity.probe_mac,
                                            collectionEntity.recordStartTime
                                        )
                                )
                            }
                        }
                        //灭菌压力
                        if (maxAirPressureList.size > 0) {
                            complianceResult.sterilizationPressure =
                                "最低：${minAirPressureList.min()}mbar 最高：${maxAirPressureList.max()}mbar 平均：${avgAirPressureList.average()}mbar"
                        }
                    }
                } else {
                    //======================清洗消毒======================
                    //维持时间======================
                    val maxStartMaintainTimeList = arrayListOf<Long>()
                    val mixEndMaintainTime = arrayListOf<Long>()
                    val probeRecordMapList = arrayListOf<HashMap<Long, Double>>()
                    for (i in collectionRecordList.indices) {
                        val collectionEntity = collectionRecordList[i]
                        maxStartMaintainTimeList.add(collectionEntity.recordStartTime.toLong())
                        mixEndMaintainTime.add(collectionEntity.recordStartTime.toLong() + collectionEntity.recordNum)
                        val probeRecordList = DbHelper.init().getProbeRecordDao()
                            .getProbeRecordList(
                                collectionEntity.probe_mac,
                                collectionEntity.recordStartTime
                            )
                        //key:时间。value:温度数值
                        val simgleProbeRecordMap = hashMapOf<Long, Double>()
                        probeRecordList.forEachIndexed { index, probeRecordEntity ->
                            simgleProbeRecordMap[probeRecordEntity.recordStartTime.toLong() + index] =
                                probeRecordEntity.temperature
                        }
                        probeRecordMapList.add(simgleProbeRecordMap)
                    }
                    //这边开始取交集
                    val maxStartMaintainTime = maxStartMaintainTimeList.max()
                    val minEndMaintainTime = mixEndMaintainTime.min()
                    val allgreaterThanTimeList = arrayListOf<Long>()
                    for (i in maxStartMaintainTime..minEndMaintainTime) {
                        var allgreaterThan = true
                        //判断同一时间内的数值是否都大于指定的温度
                        for (hashMap in probeRecordMapList) {
                            val value = hashMap[i]
                            if (value == null || value < wd) {
                                allgreaterThan = false
                            }
                        }
                        if (allgreaterThan) {
                            allgreaterThanTimeList.add(i)
                        } else if (allgreaterThanTimeList.size > 0) {
                            break
                        }
                    }
                    //起始和结束
                    //维持时间计算完成
                    if (allgreaterThanTimeList.size >= 2) {
                        complianceResult.maintenanceTime =
                            (allgreaterThanTimeList[allgreaterThanTimeList.size - 1] - allgreaterThanTimeList[0]).toString()
                    }
                    //A0======================
                    //固定判断时间65， t*10^(T-80)/10（t ——消毒时间，以s计 T ——消毒温度）
                    //开始大于65开始计算，用那个公式。小于65结束然后全部叠加
                    val A0_BASE_WENDU = 65
                    val a0List = arrayListOf<Double>()
                    for (i in collectionRecordList.indices) {
                        val collectionEntity = collectionRecordList[i]
                        //温度传感器存在
                        if (collectionEntity.isExistTemp()) {
                            val probeRecordList = DbHelper.init().getProbeRecordDao()
                                .getProbeRecordList(
                                    collectionEntity.probe_mac,
                                    collectionEntity.recordStartTime
                                )
                            val simgleA0List = arrayListOf<Double>()
                            for (probeRecordEntity in probeRecordList) {
                                //默认大于65度，然后算A0值从大于等于65到小于65截止
                                if (probeRecordEntity.temperature >= A0_BASE_WENDU) {
                                    simgleA0List.add(10.0.pow((probeRecordEntity.temperature - 80) / 10))
                                } else if (simgleA0List.size > 0) {
                                    break
                                }
                            }
                            //开始大于65开始计算，用那个公式。小于65结束然后全部叠加
                            if (simgleA0List.isNotEmpty()) {
                                a0List.add(simgleA0List.sum())
                            }
                        }
                    }
                    //A0结果显示，一条就显示单个，多条显示最小最大区间
                    if (a0List.size == 1) {
                        complianceResult.a0Value = a0List[0].toString()
                    } else if (a0List.size > 1) {
                        complianceResult.a0Value = "${a0List.min()}-${a0List.max()}"
                    } else {
                        calculationLocalResult.noComplianceResult = "数据异常，无法评估！"
                    }
                }
            } else {
                //真空处理
                //真空外部默认只能选一条，计算也是按一条计算
                val collectionEntity = collectionRecordList[0]
                if (collectionEntity.isExistAirPressure()) {
                    val probeRecordListAirPressureMin = DbHelper.init().getProbeRecordDao()
                        .getProbeRecordListAirPressureMinData(
                            collectionEntity.probe_mac,
                            collectionEntity.recordStartTime
                        )
                    val probeRecordListLimit =
                        DbHelper.init().getProbeRecordDao().getProbeRecordListLimit(
                            collectionEntity.probe_mac,
                            collectionEntity.recordStartTime,
                            probeRecordListAirPressureMin.id,
                            wd.toInt()
                        )
                    //按分钟显示，数据间隔默认是秒
                    complianceResult.pressureRiseRate =
                        "${(probeRecordListLimit[probeRecordListLimit.size - 1].airPressure - probeRecordListLimit[0].airPressure) / (wd.toDouble() / 60)}千帕/分钟"
                } else {
                    calculationLocalResult.noComplianceResult =
                        "选择的测量数据中没有压力数据，无法评估！"
                }
            }
            calculationLocalResult.complianceResult = complianceResult
        }

        //返回结果数据
        ApiResponse(0, "", calculationLocalResult)
    }

    /**
     * 探头采集记录列表
     */
    suspend fun getLocalRecordCurveList(ids: ArrayList<Int>): ApiResponse<ArrayList<ProbeAllInfo>> {
        return withContext(Dispatchers.IO) {
            val collectionRecordList =
                DbHelper.init().getCollectionDao().getCollectionRecordList(ids)
            val responseData = ArrayList<ProbeAllInfo>()
            collectionRecordList.forEach {
                val probeRecordList = DbHelper.init().getProbeRecordDao()
                    .getProbeRecordList(it.probe_mac, it.recordStartTime)
                val probeAllInfo = ProbeAllInfo(
                    it.probe_mac,
                    it.sw,
                    it.hw,
                    it.battery,
                    it.feature,
                    it.wayNum,
                    it.wayIndex,
                    it.recordSamplingInterval,
                    it.recordStartTime,
                    it.model,
                    it.recordNum
                )
                probeAllInfo.probeSamplingRecordInfoList.addAll(probeRecordList)
                responseData.add(probeAllInfo)
            }
            ApiResponse(0, "", responseData)
        }
    }
}